package com.krtech.wecard.module.mayi.controller;

import cn.dev33.satoken.SaManager;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.framework.model.CommRes;
import com.krtech.wecard.framework.security.Inner;
import com.krtech.wecard.framework.utils.LoginUtil;
import com.krtech.wecard.module.mayi.MayiPayEnums;
import com.krtech.wecard.module.mayi.entity.MaYiUser;
import com.krtech.wecard.module.mayi.entity.MayiPayList;
import com.krtech.wecard.module.mayi.service.MayiPayListService;
import com.krtech.wecard.module.sys.entity.SysDept;
import com.krtech.wecard.module.sys.entity.SysSchoolInfo;
import com.krtech.wecard.module.sys.entity.SysUser;
import com.krtech.wecard.module.sys.service.SysUserService;
import com.krtech.wecard.module.util.SmsUtil;
import com.krtech.wecard.module.util.VerifyCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/mayiUser")
@Slf4j
@Api(value = "蚂蚁阅读量账号管理")
public class MayiUserManagerController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private MayiPayListService mayiPayListService;

    /**
     * 时间有效时间
     */
    private static final Integer CODE_EXPIRED = 1;

//    @GetMapping("/getVerificationCode")
//    @ApiOperation(value = "获得验证码")
//    @Inner(value = false)
//    public CommRes getVerificationCode(String phone) throws Exception {
//
//        String currentVerification = SaManager.getSaTokenDao().get("getVerificationCode:"+phone);
//        if (StrUtil.isNotEmpty(currentVerification)){
//            throw new BusinessException("一分钟只能获取一次验证码，请勿频繁点击");
//        }
//
//        //生成随机6位数二维码
//        String verification = RandomUtil.randomNumbers(6);
//        //AliSMS.SendSMSByAli(phone,verification);
//
//        VerifyCode verifyCode = new VerifyCode();
//        verifyCode.setCode(verification);
//        //拼接验证码
//        verifyCode.setPhone(phone);
//        verifyCode.setTime(CODE_EXPIRED.toString());
//        SmsUtil.sendSms(verifyCode);
//
//        //存入redis,并且限制过期时间，并且设置唯一键setNx，保证一个手机一分钟只能发送一次短信验证
//        SaManager.getSaTokenDao().set("getVerificationCode:"+phone,verification,CODE_EXPIRED * 60);
//
//        return CommRes.ok(verification);
//    }

    @PostMapping("/registerAccount")
    @ApiOperation(value = "注册账号")
    @Inner(value = false)
    public boolean backAdd(@RequestBody MaYiUser user) {
        //注册账号


        if (StrUtil.isEmpty(user.getPhone())){
            throw new BusinessException("必填参数电话号码不能为空（账号不能为空）");
        }

//        if (StrUtil.isEmpty(user.getVerification())){
//            throw new BusinessException("必填参数验证码不能不为空");
//        }

        String password = user.getPasswordStr();
        user.setPassword(SecureUtil.sha256(password));
        user.setCreateTime(new Date());
        if (StrUtil.isEmpty(user.getUserCode())){
            user.setUserCode(user.getPhone());
        }

        if (StrUtil.isEmpty(user.getUserName())){
            user.setUserName(user.getPhone());
        }


        return userService.save(user);
    }

    @GetMapping("/myTask")
    @ApiOperation(value = "我的任务")
    public List<MayiPayList> myTask() {
        SysUser userInfo = LoginUtil.getUserInfo();

        //应该2在最前面，1在第二，三在最后
        List<MayiPayList> list = mayiPayListService.list(new QueryWrapper<MayiPayList>()
                .eq(MayiPayList.COL_FK_USER_CODE,userInfo.getUserCode()).orderByDesc(MayiPayList.COL_STATUS));

        //重新组装一下顺序
        List<MayiPayList> resultList = new ArrayList<>();

        List<MayiPayList> runing = list.stream().filter(pay -> pay.getStatus().equals(MayiPayEnums.PAY_AND_RUNING)).collect(Collectors.toList());
        resultList.addAll(runing);

        List<MayiPayList> payAndNotRun = list.stream().filter(pay -> pay.getStatus().equals(MayiPayEnums.PAY_AND_NOT_RUN)).collect(Collectors.toList());
        resultList.addAll(payAndNotRun);

        List<MayiPayList> over = list.stream().filter(pay -> pay.getStatus().equals(MayiPayEnums.PAY_AND_RUN_OVER)).collect(Collectors.toList());
        resultList.addAll(over);

        //重新计算到达数量并返回
        resultList = resultList.stream().map(oneResult -> {
            //重新算当前完成比例
            BigDecimal realGoalCount = new BigDecimal(oneResult.getRealGoalCount());
            BigDecimal reachCount = new BigDecimal(oneResult.getReachCount());

            //比例
            BigDecimal bili = reachCount.divide(realGoalCount, 2, BigDecimal.ROUND_HALF_UP);

            if (bili.compareTo(new BigDecimal("1.00")) > 0) {
                bili = new BigDecimal("1.00");
            }

            BigDecimal goalCount = new BigDecimal(oneResult.getGoalCount());

            BigDecimal resultReachCount = goalCount.multiply(bili);
            oneResult.setReachCount(resultReachCount.intValue());

            return oneResult;
        }).collect(Collectors.toList());

        return resultList;
    }
}
